package Leetcode;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class exist {
    public static int[][] dir ={{0,1},{1,0},{-1,0},{0,-1}};
    public boolean exist(char[][] board, String word) {
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (find(board, visited, word, i, j, 0)){
                    return true;
                }
            }
        }
        return false;
    }
    public boolean find(char[][] board, boolean[][] visited, String word,int xIndex, int yIndex, int index){
        if (index == word.length()){
            return true;
        }
        if (xIndex >= board.length || yIndex >= board[0].length || xIndex < 0 || yIndex < 0 || visited[xIndex][yIndex] || board[xIndex][yIndex] != word.charAt(index)) {
            return false;
        }
        visited[xIndex][yIndex] = true;
        for (int[] d : dir) {
            if (find(board, visited, word, xIndex + d[0], yIndex + d[1], index + 1)){
                return true;
            }
        }
        visited[xIndex][yIndex] = false;
        return false;
    }
}
